package com.punch.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punch.common.dto.course.CourseTeachingDTO;
import com.punch.common.dto.user.user.RedisUserDTO;
import com.punch.common.enums.user.role.UserRoleEnum;
import com.punch.common.enums.user.user.AuditStatusEnum;
import com.punch.common.exception.BusinessException;
import com.punch.common.exception.CommonExceptionEnum;
import com.punch.common.redis.utils.UserUtil;
import com.punch.common.vo.course.CourseTeachingVO;
import com.punch.common.vo.course.report.OrganReportVO;
import com.punch.course.exception.CourseExceptionEnum;
import com.punch.course.mapper.CourseMapper;
import com.punch.course.mapper.CourseTeachingMapper;
import com.punch.course.model.CourseLibrary;
import com.punch.course.model.CourseTeaching;
import com.punch.course.model.PunchCourse;
import com.punch.course.service.CourseLibraryService;
import com.punch.course.service.CourseTeachingService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * CourseService-课程授课 实现类
 *
 * @author xiaol
 * @version 1.0.0
 * @since 2020/7/14 10:51
 */
@Service
@Deprecated
public class CourseTeachingServiceImpl extends ServiceImpl<CourseTeachingMapper, CourseTeaching> implements CourseTeachingService {

    @Resource
    private CourseMapper courseMapper;

    @Autowired
    private CourseLibraryService courseLibraryService;

    /**
     * 保存授课申请
     *
     * @param courseTeachingDTO 授课申请
     * @return id
     */
    @Override
    public Long saveCourseTeaching(CourseTeachingDTO courseTeachingDTO) {
        //查看对该学校是否已经申请授权,如果存在申请中/已完成的则不能在添加
        QueryWrapper<CourseTeaching> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseTeaching::getCourseId, courseTeachingDTO.getCourseId()).eq(CourseTeaching::getSchoolId, courseTeachingDTO.getSchoolId())
                .in(CourseTeaching::getStatus, 0, 1);
        int count = count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(CourseExceptionEnum.COURSE_TO_TEACHING_EXIST);
        }
        CourseTeaching courseTeaching = new CourseTeaching();
        BeanUtils.copyProperties(courseTeachingDTO, courseTeaching);
        RedisUserDTO loginUser = UserUtil.getLoginUser();
        courseTeaching.setCreateId(loginUser.getUserId());
        courseTeaching.setCreateName(loginUser.getUsername());
        save(courseTeaching);
        return courseTeaching.getId();
    }

    /**
     * 申请授课列表
     *
     * @param courseId 课程id
     * @return list
     */
    @Override
    public List<CourseTeachingVO> listCourseTeaching(Long courseId) {
        QueryWrapper<CourseTeaching> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseTeaching::getCourseId, courseId).orderByDesc(CourseTeaching::getUpdateTime);
        List<CourseTeaching> list = list(queryWrapper);
        List<CourseTeachingVO> retList = new ArrayList<>();
        list.forEach(courseTeaching -> {
            CourseTeachingVO courseTeachingVO = new CourseTeachingVO();
            BeanUtils.copyProperties(courseTeaching, courseTeachingVO);
            courseTeachingVO.setTeachingId(courseTeaching.getId());
            courseTeachingVO.setCourseId(courseId);
            retList.add(courseTeachingVO);
        });
        return retList;
    }

    /**
     * 学校同意授课,需要把该课程添加到课程库中
     *
     * @param courseId 课程id
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void agreeCourseTeaching(Long courseId) {
        RedisUserDTO loginUser = UserUtil.getLoginUser();
        //只有学校才能同意授课
        if (loginUser.getRoleId() != UserRoleEnum.SCHOOL.getCode()) {
            throw new BusinessException(CourseExceptionEnum.ONLY_SCHOOL_CAN_AGREE_TEACH);
        }
        //如果该课程是学校开办的直接授课
        PunchCourse courseEX = courseMapper.selectById(courseId);
        if (courseEX == null) {
            throw new BusinessException(CourseExceptionEnum.COURSE_DETAIL_FAIL_NULL);
        }
        CourseLibrary courseLibrary = new CourseLibrary();
        courseLibrary.setCourseId(courseId);
        courseLibrary.setCreateId(loginUser.getUserId());
        //如果是机构的课程需要查询下是否已经申请授权
        if (courseEX.getRoleId() == UserRoleEnum.ORGAN.getCode()) {
            QueryWrapper<CourseTeaching> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CourseTeaching::getCourseId, courseId)
                    .eq(CourseTeaching::getStatus, 0)
                    .eq(CourseTeaching::getSchoolId, loginUser.getUserId());
            CourseTeaching courseTeachingEX = getOne(queryWrapper);
            if (courseTeachingEX == null) {
                throw new BusinessException(CourseExceptionEnum.COURSE_NOT_TO_SCHOOL);
            }
            CourseTeaching courseTeaching = new CourseTeaching();
            courseTeaching.setId(courseTeachingEX.getId());
            courseTeaching.setStatus(1);//已同意
            updateById(courseTeaching);
            courseLibrary.setOrganId(courseTeachingEX.getCreateId());
            courseLibrary.setTeacherId(courseTeachingEX.getTeacherId());
            courseLibrary.setTeacherName(courseTeachingEX.getTeacherName());
        }
        //如果是学校的课程 需要修改课程状态为  4-加入课程库(针对学校)
        if (courseEX.getRoleId() == UserRoleEnum.SCHOOL.getCode()) {
            PunchCourse course = new PunchCourse();
          //  course.setCourseStatus(AuditStatusEnum.TO_LIBRARY.getCode());
            course.setId(courseId);
            courseMapper.updateById(course);
            course = null;//help gc
        }
        //加入到课程库
        courseLibraryService.save(courseLibrary);
        courseEX = null;
        courseLibrary = null; //help gc
    }

    /**
     * 学校移除课程库id
     *
     * @param libraryId 课程库id
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void removeCourseLibrary(Long libraryId) {
        RedisUserDTO loginUser = UserUtil.getLoginUser();
        //只有学校才能操作
        if (loginUser.getRoleId() != UserRoleEnum.SCHOOL.getCode()) {
            throw new BusinessException(CourseExceptionEnum.ONLY_SCHOOL_CAN_REMOVE_LIBRARY);
        }
        CourseLibrary courseLibrary = courseLibraryService.getById(libraryId);
        if (courseLibrary == null) {
            throw new BusinessException(CourseExceptionEnum.COURSE_LIBRARY_NOT_EXIST);
        }
        courseLibraryService.removeById(libraryId);
        //如果是学校的课程,修改把课程状态从4-3
        if (courseLibrary.getOrganId() == null || courseLibrary.getOrganId() == 0) {
            PunchCourse punchCourse = new PunchCourse();
            punchCourse.setId(courseLibrary.getCourseId());
            punchCourse.setCourseStatus(AuditStatusEnum.PASSED.getCode());
            courseMapper.updateById(punchCourse);
        } else {
            // 如果是机构的课程，申请授课状态需要变成 已移除
            QueryWrapper<CourseTeaching> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(CourseTeaching::getCourseId, courseLibrary.getCourseId())
                    .eq(CourseTeaching::getSchoolId, loginUser.getUserId())
                    .eq(CourseTeaching::getStatus, 1);
            CourseTeaching courseTeachingEX = getOne(queryWrapper);
            if (courseTeachingEX == null) {
                throw new BusinessException(CourseExceptionEnum.COURSE_TEACHING_NOT_EXIST);
            }
            CourseTeaching courseTeaching = new CourseTeaching();
            courseTeaching.setStatus(2);
            courseTeaching.setId(courseTeachingEX.getId());
            updateById(courseTeaching);
            removeById(courseTeaching);
        }
    }

    /**
     * 取消授课申请
     *
     * @param courseId   课程id
     * @param teachingId 授课申请id
     */
    @Override
    public void deleteCourseTeaching(Long courseId, Long teachingId) {
        //说明是学校端课程列表取消
        CourseTeaching courseTeachingEX = null;
        if (teachingId == 0L) {
            QueryWrapper<CourseTeaching> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(CourseTeaching::getSchoolId, UserUtil.getLoginUserId())
                    .eq(CourseTeaching::getCourseId, courseId)
                    .eq(CourseTeaching::getStatus, 0);
            courseTeachingEX = getOne(queryWrapper);
            teachingId = courseTeachingEX.getId();
        } else {
            courseTeachingEX = getById(teachingId);
        }
        //查看状态是不是申请中
        if (courseTeachingEX == null) {
            throw new BusinessException(CourseExceptionEnum.COURSE_TEACHING_NOT_EXIST);
        }
        if (courseTeachingEX.getStatus() != 0) {
            throw new BusinessException(CourseExceptionEnum.COURSE_TEACHING_STATUS_ERROR);
        }
        if (!removeById(teachingId)) {
            throw new BusinessException(CommonExceptionEnum.DELETE_ERROR);
        }

    }

    /**
     * 获取通过申请的机构信息集合
     *
     * @param schoolId
     * @return
     */
    @Override
    public List<OrganReportVO> getOrganList(Long schoolId) {
        List<OrganReportVO> courseTeachings = this.getBaseMapper().getOrganList(schoolId);
        return courseTeachings;
    }
}
